package com.example.demo.interceptor;

import com.example.demo.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 从请求中获取 token
        String token = request.getHeader("userInfo_token");
        // 2. 校验 token, 判断是否放行
        Claims claims = JwtUtils.parseToken(token);
        if(claims == null){
            // 拦截
            response.setStatus(401);
            return false;
        }

        return true;
    }
}
